package com.example.security.intercept;

import com.example.security.annotation.AuthMethod;
import com.example.core.controller.BaseController;
import com.example.security.funtion.FunctionContext;
import com.example.core.utils.Result;
import com.googlecode.aviator.AviatorEvaluator;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Service
public class UrlHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        boolean flag = true;
        if (o instanceof HandlerMethod) {
            Object bean = ((HandlerMethod) o).getBean();
            Method method = ((HandlerMethod) o).getMethod();
            if (bean instanceof BaseController && method.isAnnotationPresent(AuthMethod.class)) {
                flag = (Boolean) AviatorEvaluator.execute(method.getAnnotation(AuthMethod.class).expression(), new FunctionContext(request, response, (BaseController) bean, ((BaseController) bean).getService()));
            }
        }
        if (!flag) {
            Result.noAuth(response);
        }
        return flag;
    }
}
